/**
 * 
 */
package com.jolestar.yayaweibotong.task;

import static java.util.logging.Level.SEVERE;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.jolestar.yayaweibotong.YaYaConstants;
import com.jolestar.yayaweibotong.YayaException;
import com.jolestar.yayaweibotong.dao.AccountDomain;
import com.jolestar.yayaweibotong.dao.StatusDomain;
import com.jolestar.yayaweibotong.dao.UserDomain;
import com.jolestar.yayaweibotong.service.UserService;

/**
 * @author <a href="mailto:jolestar@gmail.com">Jolestar</a>
 */
public class SyncTask {

	static SyncTask instance = new SyncTask();

	private static final Logger log = Logger
			.getLogger(SyncTask.class.getName());

	private UserService userService = UserService.ServiceHolder.getInstance();

	public void doTask() {
		log.info("sync task start.");
		long start = System.currentTimeMillis();
		try {
			int startIndex = 0;
			int batchSize = 100;
			List<UserDomain> users = userService
					.getUsers(startIndex, batchSize);
			while (!users.isEmpty()) {
				for (UserDomain user : users) {
					AccountDomain masterAccount = user.getMasterAccount();
					List<AccountDomain> slaveAccounts = user.getSlaveAccounts();
					if (!user.isActivity() || masterAccount.isSuspend() || slaveAccounts.isEmpty()) {
						continue;
					}
					List<StatusDomain> statuses = null;
					try {
						statuses = masterAccount
								.getServiceType()
								.getStatusService()
								.getLatestStatuses(masterAccount,
										masterAccount.getLastSyncStatusId());
						masterAccount.setError("");
					} catch (Exception e) {
						log.log(Level.SEVERE,
								"获取主帐号最新微博失败。用户:" + user.getEmail()
										+ ",account:"
										+ masterAccount.getKeyName()
										+ ", token:" + masterAccount.getToken()
										+ ",tokenSecret:"
										+ masterAccount.getTokenSecret());
						log.log(Level.SEVERE, e.getMessage(), e);
						masterAccount.setError(e.getMessage());
						long currentTime = System.currentTimeMillis();
						masterAccount.suspendTo(new Date(currentTime+YaYaConstants.TEN_MINUTE));
						masterAccount.save();
						continue;
					}
					masterAccount.setLastSyncDate(new Date());
					if (statuses.isEmpty()) {
						masterAccount.save();
						continue;
					}
					//反向 先发旧的再发新的
					Collections.reverse(statuses);
					for (AccountDomain slaveAccount : slaveAccounts) {
						if (!slaveAccount.isActivity() || slaveAccount.isSuspend()) {
							continue;
						}
						for (StatusDomain status : statuses) {
							try {
								slaveAccount.getServiceType()
										.getStatusService()
										.updateStatus(slaveAccount, status);
								slaveAccount.setError("");
							} catch (Exception e) {
								log.log(Level.SEVERE,
										"更新微博失败。用户:" + user.getEmail()
												+ ",account:"
												+ slaveAccount.getKeyName()
												+ ", token:" + slaveAccount.getToken()
												+ ",tokenSecret:"
												+ slaveAccount.getTokenSecret());
								log.log(SEVERE, e.getMessage(), e);
								slaveAccount.setError(e.getMessage());
								long currentTime = System.currentTimeMillis();
								masterAccount.suspendTo(new Date(currentTime+YaYaConstants.TEN_MINUTE));
								slaveAccount.save();
								break;
							}
							slaveAccount.setLastSyncStatusId(status
									.getOriginalId());
							slaveAccount.increaseSyncToCount(1);
							status.setSynced(true);
							status.setSyncedAt(new Date());
							status.save();
							masterAccount.setLastSyncStatusId(status
									.getOriginalId());
						}
						slaveAccount.setLastSyncDate(new Date());
						slaveAccount.save();
					}
					masterAccount.save();
				}
				startIndex += batchSize;
				users = userService.getUsers(startIndex, batchSize);
			}
		} catch (Exception e) {
			log.log(SEVERE, e.getMessage(), e);
		}
		log.info("fetch task end.use time:"
				+ (System.currentTimeMillis() - start));
	}

	public static SyncTask getInstance() {
		return instance;
	}
}
